package impl

import (
	"context"
	"fmt"
	"time"

	"gitee.com/ChangPaoZhe/devops/apps/user"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/bson"
	"golang.org/x/crypto/bcrypt"
)



func DefaultRandom()  string  {
	randomUUID, err := uuid.NewRandom()
	if err != nil {
		panic(err)
	}
	return   randomUUID.String()
}

func  NewDefaultRegisterRequest() *user.RegisterRequest {
	return  &user.RegisterRequest{

	}
}

func  NewDefaultUser()  *user.User {
	return  &user.User{
		Role: user.Role_GUEST,
		CreateAt: time.Now().Unix(),
	}
}

func  NewDefaultCheckPasswordRequest() *user.CheckPasswordRequest {
	return  &user.CheckPasswordRequest{

	}
}


// 注册用户
func (u *UserImpl)  Register(ctx  context.Context,req  *user.RegisterRequest) (*user.User, error)  {
	if  req.User.Username== ""  || req.Password == ""{
		return  nil,fmt.Errorf("user or  password is null ")
	}
	collection:=u.MogoDb.Collection("user")
	saveuser:=NewDefaultUser()
	saveuser.Username=req.User.Username
	saveuser.Address=req.User.Address
	saveuser.PhoneNumber=req.User.PhoneNumber
	saveuser.Id=DefaultRandom()
	hashPassword,err:=bcrypt.GenerateFromPassword([]byte(req.Password),bcrypt.DefaultCost)
	if err!=nil {
		return nil,err
	}
	saveuser.HashPasswd=string(hashPassword)
	_,err=collection.InsertOne(ctx, saveuser)
	if err != nil {
		return nil, err
	}

	return saveuser,nil 
}

func NewDefaultSearchRequest() *user.SearchRequest {
	return &user.SearchRequest{

	}
}

func NewDefaultSearchReponseResource()  *user.SearchReponseUser  {
	return  &user.SearchReponseUser{

	}
}
func (u *UserImpl) CheckPassword(ctx  context.Context,req  *user.CheckPasswordRequest) (*user.User, error){
	if  req.Username == "" || req.Password == ""{
		return  nil,fmt.Errorf("user or  password is null ")
	}
	saveuser:=NewDefaultUser()
	collection:=u.MogoDb.Collection("user")
	filter:=bson.M{"username": req.Username}
	u.logger.Info().Msg(fmt.Sprintf("check user:%s,passwd:%s,filter:%v",req.Username,req.Password,filter))

	err:=collection.FindOne(ctx, filter).Decode(saveuser)
	if err != nil {
		u.logger.Error().Msg(fmt.Sprintf("查询错误:%s",err.Error()))
		return nil, err
	}
	err=bcrypt.CompareHashAndPassword([]byte(saveuser.HashPasswd), []byte(req.Password))
	if err != nil {
		u.logger.Error().Msg(fmt.Sprintf("用户:%s 校验失败",req.Username))
		return nil, err
	}
	return saveuser,nil 
}
func (u *UserImpl)   Search(ctx  context.Context,req  *user.SearchRequest) (*user.SearchReponseUser, error){
	filter:=bson.M{}
	if req.Username == ""   {
		if  (req.Role != user.Role_ADMIN  && req.Role!= user.Role_GUEST  && req.Role!=user.Role_USER) {
			return  nil,fmt.Errorf("user or  role is null ")
		}else {
			filter=bson.M{"role": int(req.Role)}
		}

	}else  {
		if  (req.Role != user.Role_ADMIN  && req.Role!= user.Role_GUEST  && req.Role!=user.Role_USER) {
			filter=bson.M{"username": req.Username}
		}else  {
			filter=bson.M{"$and": []bson.M{bson.M{"username": req.Username},bson.M{"role": int(req.Role)}}}
		}
	}
	u.logger.Info().Msg(fmt.Sprintf("Search :%s,role:%s,filter:%v",req.Username,req.Role,filter))
	collection:=u.MogoDb.Collection("user")
	cursor,err:=collection.Find(ctx, filter)
	if err != nil {
		u.logger.Error().Msg(fmt.Sprintf("查询失败%s",err))
		return nil, err
	}
	var   Response []*user.User
	err=cursor.All(ctx, &Response)
	if err !=nil  {
		u.logger.Error().Msg(fmt.Sprintf("解析失败%s",err))
		return nil,err
	}
	if len(Response) == 0 {
		msg:=fmt.Sprintf("查询信息Username:%s or  Role:%s 无返回数据",req.Username,req.Role)
		u.logger.Error().Msg(msg)
		return nil,fmt.Errorf(msg)
	}
	u.logger.Info().Msg(fmt.Sprintf("查询结果%#v",Response))
	resouce:=NewDefaultSearchReponseResource()
	for  _,user:=range  Response {
		u:=NewDefaultUser()
		u.Username=user.Username
		u.Address=user.Address
		u.PhoneNumber=user.PhoneNumber
		resouce.Values = append(resouce.Values, u)
	}
	resouce.Values=Response
	resouce.Totalcount=int64(len(Response))
	return resouce,nil
}